#include "stm32f10x.h"                  // Device header
#include "MySPI.h"

#include "GPIO.h"

/*
	*@brief		用户根据写入BitValue设置CS引脚的高低，外部可调用
	*@param		BitValue 可以是1，或0
	*@retval	NO
*/
void MySPI_W_CS(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOB, SPI_CS, (BitAction)BitValue);
}

/*
	*@brief		硬件初始化SPI1
	*@param		NO
	*@retval	NO
*/
void MySPI_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);	//开启外部时钟信号
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);	//开启SPI2的时钟
	
	GPIO_InitTypeDef GPIO_InitStructure;
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;	//配置CS为推挽输出
	GPIO_InitStructure.GPIO_Pin = SPI_CS;				//配置CS端口
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	//配置速度，最高速
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;	//复用推挽输出
	GPIO_InitStructure.GPIO_Pin = SPI_SCK | SPI_MOSI;	//配置端口
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	//速度
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;		//上拉输入
	GPIO_InitStructure.GPIO_Pin = SPI_SIMO;				//配置端口
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	//速度
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	SPI_InitTypeDef SPI_InitStructure;
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;	//时钟频率72MHz/4~=5625Hz
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;						//边沿采样，
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;							//时钟极性，默认低电平
	SPI_InitStructure.SPI_CRCPolynomial = 10;							//CRC校验位，不用
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;					//配置8位还是16位数据帧
	SPI_InitStructure.SPI_Direction = SPI_Direction_1Line_Tx;	//标准模式，双线全双工	*
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;					//高位先行传输，就是从高位到低位传输数据
	SPI_InitStructure.SPI_Mode = SPI_Mode_Master;			//选择SPI模式是主机
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;				//软件Nss实际上不会用到
	SPI_Init(SPI2,&SPI_InitStructure);
	
	SPI_Cmd(SPI2,ENABLE);
	
	MySPI_W_CS(1);
	
}

void MySPI_Start(void)
{
	MySPI_W_CS(0);
}

void MySPI_Stop(void)
{
	MySPI_W_CS(1);
}

uint8_t MySPI_SwapByte(uint8_t ByteSend)
{
	while(SPI_I2S_GetFlagStatus(SPI2,SPI_I2S_FLAG_TXE) != SET );	

	SPI_I2S_SendData(SPI2,ByteSend);	//发送字节
	
	while(SPI_I2S_GetFlagStatus(SPI2,SPI_I2S_FLAG_RXNE) != SET );
//	while(SPI_I2S_GetFlagStatus(SPI2,SPI_I2S_FLAG_BSY) != SET );	//等待发送完成
	
	return SPI_I2S_ReceiveData(SPI2);	//返回一个交换的字节
}
